/*
 * Copyright 2009 Prime Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.primefaces.facestrace.utils;

import java.util.GregorianCalendar;

import javax.faces.context.FacesContext;

import org.primefaces.facestrace.TraceData;

public class TraceUtils {

	public static long getCurrentTimeinMillis(){
		GregorianCalendar cd = new GregorianCalendar();
		return cd.getTimeInMillis();
	}
	
	public static TraceData getTraceData() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		TraceData traceData =(TraceData) facesContext.getApplication().createValueBinding("#{facesTraceData}").getValue(facesContext); 
		if( traceData == null)
			traceData = new TraceData();
		return traceData;
	}
	
	public static String getResourceFileExtension(String resourcePath) {
		String parsed[] = resourcePath.split("\\.");
		
		return parsed[parsed.length -1];
	}
	
	//We need these three resource types for now
	public static String getContentType(String resourceType) {
		String contentType = null;
		if(resourceType.equals("js"))
			contentType = "text/javascript";
		else if(resourceType.equals("css"))
			contentType = "text/css";
		else if(resourceType.equals("gif"))
			contentType = "image/gif";
		else if(resourceType.equals("png"))
			contentType = "image/png";
		else if(resourceType.equals("jpg"))
			contentType = "image/jpeg";
		
		return contentType;
	}
	
	public static boolean isTraceDisabled(FacesContext facesContext) {
		String paramValue = facesContext.getExternalContext().getInitParameter("org.facestrace.DISABLE_TRACE");
		
		if(paramValue == null)
			return false;
		else
			return Boolean.valueOf(paramValue).booleanValue();
	}
	
	public static String getActionURL(FacesContext facesContext) {
		String viewId = facesContext.getViewRoot().getViewId();
		
		return facesContext.getApplication().getViewHandler().getActionURL(facesContext, viewId);
	}
	
	public static String getResourceURL(FacesContext facesContext, String resource) {
		String actionURL = facesContext.getExternalContext().encodeResourceURL(getActionURL(facesContext));
		
		if(actionURL.contains("?"))
			actionURL = actionURL + "&facestraceResource=" + resource;
		else
			actionURL = actionURL + "?facestraceResource=" + resource;
		
		return actionURL;
	}
	
	
}
